
import os
import datetime
import re
import gradio as gr
from .batch_text_to_markdown import merge_repository



import random
import string



import ssl

home = os.path.expanduser("~")

def get_default_output_folder():
    return os.path.join(home, "Downloads")


def generate_filename():
    """生成基于时间和随机字符的文件名"""
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    random_string = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
    return f"src-merge-{timestamp}_{random_string}.md"




examples=[
        ["/Users/Shared/work_cache/input_cache/src", "", "py,html,js,md,cpp,h,c,ipynb"],
        ["/Users/Shared/work_cache/input_cache/src", "/Users/Shared/work_cache/output_cache/merged_src.md", "py,html,js,md,cpp,h,c,ipynb"],
        ["/path/to/example/repo", "/path/to/output/merged_example.md", "py,html,js,md,cpp,h,c"],
        ["/path/to/another/repo", "/path/to/output/another_merged.md", "cpp,h,c"]
    ]


# 禁用SSL验证
ssl._create_default_https_context = ssl._create_unverified_context

def process_folder(input_folder, output_file, file_types):
    #
    input_folder = input_folder.strip()

    if not output_file.strip():
        output_file = get_default_output_folder() + '/'+generate_filename()

    try:
        merge_repository(input_folder, output_file, file_types)
        return f"成功创建合并文档：{output_file}"
    except Exception as e:
        return f"处理过程中出错：{str(e)}"



#

description="""
选择一个文件夹，指定输出文件路径，然后选择要合并的文件类型。


jupyter可转为python代码，减少空间，例如：
jupyter nbconvert --to python <文件名>.ipynb
"""
# 创建Gradio接口
iface = gr.Interface(
    fn=process_folder,
    inputs=[
        gr.Textbox(label="输入文件夹路径"),
        gr.Textbox(label="输出文件路径（包括文件名）"),
        gr.Textbox(label="文件类型（用逗号分隔）", value="py,html,cpp,h,c,js,md,ipynb")
    ],
    outputs=gr.Textbox(label="处理结果"),
    title="代码仓库合并工具",
    description=description,
    examples= examples
)

# 运行Gradio应用
if __name__ == "__main__":
    # 从环境变量获取端口，如果没有设置，默认使用7860
    port = int(os.environ.get("PORT", 34921 ))

    # 启动Gradio应用，设置端口并禁用SSL
    iface.launch(server_name="0.0.0.0", server_port=port, ssl_verify=False)





#
